package cn.itcast.controller;

import cn.itcast.entity.MessageConstant;
import cn.itcast.entity.RedisMessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService service;

    @RequestMapping("/login.do")
    public Result login(HttpServletResponse resp, @RequestBody Map map) {
        //获取页面中提交的手机号和验证码
        String validateCode = map.get("validateCode").toString();
        String telephone    = map.get("phoneNumber").toString();

        //读取redis中存放的手机验证码
        String key = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        //验证码对比
        if(validateCode.equals(key)){

            //检查是否为会员，如果不是是会员则进行会员注册
            Member member = service.findByTelephone(telephone);
            if(member==null){
               //map.put("phoneNumber",telephone);
                service.add(map);
            }

            //设置cookie并发送
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//设置cookie跨服务器共享
            cookie.setMaxAge(60*60*24*5);
            resp.addCookie(cookie);

            //将member对象以json串的形式保存到redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);

            return new Result(true, MessageConstant.LOGIN_SUCCESS);

        }else{
            //验证码对比失败返回此信息
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);

        }

    }

}
